package com.example.amphibians.ui.screen

import androidx.compose.runtime.getValue
import androidx.compose.runtime.mutableStateOf
import androidx.compose.runtime.setValue
import androidx.lifecycle.ViewModel
import androidx.lifecycle.ViewModelProvider
import androidx.lifecycle.viewModelScope
import androidx.lifecycle.viewmodel.initializer
import androidx.lifecycle.viewmodel.viewModelFactory
import com.example.amphibians.AmphibianApplication
import com.example.amphibians.data.AmphibianRepository
import com.example.amphibians.network.Amphibian
import kotlinx.coroutines.launch
import retrofit2.HttpException
import java.io.IOException

class AmphibianViewModel(private val amphibianRepository: AmphibianRepository) : ViewModel() {
    var amphibianState: AmphibianState by mutableStateOf(AmphibianState.Loading)
        private set

    init {
        getAmphibians()
    }

    fun getAmphibians() {
        amphibianState = AmphibianState.Loading
        viewModelScope.launch {
            amphibianState = try {
                AmphibianState.Success(amphibianRepository.getAmphibians())
            } catch (e: IOException) {
                AmphibianState.Error
            } catch (e: HttpException) {
                AmphibianState.Error
            }
        }
    }

    companion object {
        val Factory: ViewModelProvider.Factory = viewModelFactory {
            initializer {
                val application = this[ViewModelProvider.AndroidViewModelFactory.APPLICATION_KEY] as AmphibianApplication
                AmphibianViewModel(application.container.amphibianRepository)
            }
        }
    }
}

sealed interface AmphibianState {
    data class Success(val amphibians: List<Amphibian>) : AmphibianState
    data object Loading: AmphibianState
    data object Error: AmphibianState
}
